//
//  PersonArrayController.m
//  Cabinet
//
//  Created by Florent Montsegur on 21/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PersonArrayController.h"

@implementation PersonArrayController
@synthesize searchNom;
@synthesize searchPrenom;


- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (void)awakeFromNib  
{  
    NSSortDescriptor *sortnom = [[NSSortDescriptor alloc] initWithKey:@"Nom" ascending:YES];
    NSSortDescriptor *sortprenom = [[NSSortDescriptor alloc] initWithKey:@"Prenom" ascending:YES];
    [self setSortDescriptors:[NSArray arrayWithObjects:sortnom, sortprenom, nil]]; 
    
    [super awakeFromNib];  
}

- (IBAction)searchAction:(id)sender
{
    NSLog(@"%@ %@", [[self searchPrenom] stringValue], [[self searchNom] stringValue]);
    [self rearrangeObjects];
}

- (NSArray *)arrangeObjects:(NSArray *)objects
{
    NSString *patternNom = [[self searchNom] stringValue];
    NSString *patternPrenom = [[self searchPrenom] stringValue];
	
    if ( ([patternNom isEqualToString:@""]) && ([patternPrenom isEqualToString:@""]) )
		return [super arrangeObjects:objects];   
    
    NSMutableArray *matchedObjects = [NSMutableArray arrayWithCapacity:[objects count]];
    
    // case-insensitive search
    NSString *lowerSearchNom = [patternNom lowercaseString];
    NSString *lowerSearchPrenom = [patternPrenom lowercaseString];
    
	NSEnumerator *oEnum = [objects objectEnumerator];
    id item;	
    while (item = [oEnum nextObject])
	{
		//  Use of local autorelease pool here is probably overkill, but may be useful in a larger-scale application.
		@autoreleasepool {
			NSString *lowerName = [[item valueForKeyPath:@"nom"] lowercaseString];
        NSString *lowerFirstname = [[item valueForKeyPath:@"prenom"] lowercaseString];
        
        if ( (![patternNom isEqualToString:@""]) && (![patternPrenom isEqualToString:@""]) )
        {
            if ( ([lowerName rangeOfString:lowerSearchNom].location == 0) &&  
                ([lowerFirstname rangeOfString:lowerSearchPrenom].location == 0) )
                [matchedObjects addObject:item];
			}
        else if(![patternNom isEqualToString:@""])
        {
            if ([lowerName rangeOfString:lowerSearchNom].location == 0)
                [matchedObjects addObject:item];
        }
        else if(![patternPrenom isEqualToString:@""])
        {
            if ([lowerFirstname rangeOfString:lowerSearchPrenom].location == 0)
                [matchedObjects addObject:item];
        }
        
		}
    }
    
    return [super arrangeObjects:matchedObjects];
}

@end
